package com.xiaoyu.cloud.interceptor;

import com.xiaoyu.common.core.currentUser.TransmittableThreadLocalRequestHeaders;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author zgb
 * @desc header中的sessionId>redis>TransmittableThreadLocalCurrentUser
 * @date 2023-08-01 17:51:34
 */
@Slf4j
public class HeaderTransInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
        log.debug("AuthHeaderTransInterceptor:" + Thread.currentThread().getName());

        String url0 = request.getRequestURI();
        String url1 = request.getContextPath();
        log.debug("完整地址：" + url0);
        log.debug("返回当前页面所在的应用的名字：" + url1);
        log.debug("返回当前页面所在的应用的名字长度：" + url1.length());
        // 获取请求地址
        String url = request.getRequestURI().substring(request.getContextPath().length());
        log.debug("截取后的地址：" + url);

        long currentThreadId = Thread.currentThread().getId();
        log.info("VersionGrayGlobalFilter.currentThreadId:" + currentThreadId);
        String requestedSessionId = request.getRequestedSessionId();
        log.info("VersionGrayGlobalFilter.requestedSessionId:" + requestedSessionId);
        Map<String, List<String>> map = new HashMap<>();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                if (StringUtils.isNotBlank(values)) {
                    String[] split = values.split(", ");
                    List<String> stringList = Stream.of(split).collect(Collectors.toList());
                    map.put(name, stringList);
                }
            }
        }

        MultiValueMap<String, String> headers2 = CollectionUtils.toMultiValueMap(map);
        HttpHeaders headers = new HttpHeaders(headers2);
        //线程安全上下文
        TransmittableThreadLocalRequestHeaders.set(headers);

        return true;
    }


}
